const { login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')

// 获取 cookie 的过期时间
const getCookieExpires = () => {
    const d = new Date()
    d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
    console.log('d.toGMTString() is ', d.toGMTString())
    return d.toGMTString()
}

const handleUseroOuter = (req, res) => {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]

    // 登陆
    if (method === "POST" && path === '/api/user/login') {
        const { username, password } = req.body
        const res = login(username, password)
        return res.then(data => {
            console.log('data', data);
            if (data.username) {
                res.setHeader('Set-Cookie', `username=${data.username}; path=/; httpOnly; expires=${getCookieExpires()}`)
                return new SuccessModel()
            }
            return new ErrorModel('登陆失败')
        })
    }

    if (method === 'GET' && req.path === '/api/user/login-test') {
        if (req.cookie.username) {
            return Promise.resolve(new SuccessModel())
        }
        return Promise.resolve(new ErrorModel('尚未登录'))
    }
}

module.exports = handleUseroOuter